//
//  XYCallBackVC.m
//  Zhihuijinfu
//
//  Created by XY Lv on 17/3/22.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "XYCallBackVC.h"
#import "XYHUD.h"
#import "XYTextView.h"
#import "XYCommon.h"
#import "XYAddPhotoCollectionCell.h"
#import "LGPhoto.h"
#define xyHeaderH  xy(200)
#import "WDBusinessDetailController.h"
#import "XYMapViewController.h"
#import "XYMapManager.h"
#import "XYSubviewsStyle.h"
@interface XYCallBackVC ()<UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIActionSheetDelegate,UINavigationControllerDelegate,LGPhotoPickerViewControllerDelegate,UIImagePickerControllerDelegate,LGPhotoPickerBrowserViewControllerDataSource,LGPhotoPickerBrowserViewControllerDelegate,XYPhotoCellDelegate>
{
    XYTextView * _xyTextView;
    UIButton *   _xyLocalBtn;
    UILabel   *  _xyRecordTextLabel;
    UICollectionView * _xyCollectionView;
    NSMutableArray *   _xyImgMArr;
    CGFloat            _xyItemW;
    CGFloat            _xyItemH;
    LGShowImageType  _showType;
    UIView *    _xyHeaderView;
    NSMutableArray * _xyMarkMArr;
    BOOL             _xyIsEdit;
    NSMutableArray * _xyWillDeleteMArr;
    NSString *       _xyFollowId;
    XYMapManager  *  _xyMapManager;
    NSString      *  _xyLocalStr;
    double           _xyLatitude;
    double           _xyLongitude;
    

}
@end

@implementation XYCallBackVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self xyInitMArr];
    if([self.xyFollowType isEqualToString:@"2"]){
        [self loadNavItemWithLeftAction:@selector(xyCancelBtnClick:) leftBtnStr:@"取消" title:@"面访签到" rihgtAction:@selector(xySureBtnClick:) rightStr:@"发布"];

        [self xyLayoutCollectionView];
        [self xyLayoutHeaderView];
        [self xyLayoutLocalView];
        [self xyLayoutTextView];
        [self xyLayoutRecordTextLabel];
        [self xyGetLocal];

    }else if([self.xyFollowType isEqualToString:@"1"]){
        [self loadNavItemWithLeftAction:@selector(xyCancelBtnClick:) leftBtnStr:@"取消" title:@"电话回访" rihgtAction:@selector(xySureBtnClick:) rightStr:@"发布"];

        [self xyLayoutHeaderView];
        [self xyLayoutTextView];
        [self xyLayoutRecordTextLabel];

    }

}

- (void)xyInitMArr{
    _xyImgMArr = [[NSMutableArray alloc]init];
    _xyWillDeleteMArr = [[NSMutableArray alloc]init];
    _xyMapManager = [XYMapManager shareManager];
}

- (void)xyLayoutHeaderView{

    _xyHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WDScreenW, xyHeaderH)];
    [self.view addSubview:_xyHeaderView];
    
    
}

- (void)xyLayoutLocalView{

    _xyLocalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_xyHeaderView addSubview:_xyLocalBtn];
    _xyLocalBtn.frame = CGRectMake(0, 0, WDScreenW, xyLocalAlertViewH);

    _xyLocalBtn.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    
    _xyLocalBtn.titleLabel.font = [UIFont systemFontOfSize:xy(11)];
    _xyLocalBtn.titleEdgeInsets = UIEdgeInsetsMake(0,WDScreenW/2, 0, 0);
    [_xyLocalBtn setTitleColor:[UIColor colorWithRed:0.43 green:0.67 blue:0.90 alpha:1.00] forState:UIControlStateNormal];
    [_xyLocalBtn addTarget:self action:@selector(xyShowLocalBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _xyLocalBtn.layer.shadowColor = [UIColor colorWithRed:0.91 green:0.92 blue:0.92 alpha:1.00].CGColor;
    _xyLocalBtn.layer.shadowOffset =  CGSizeMake(1, 1);
    _xyLocalBtn.layer.borderWidth = 1;
    _xyLocalBtn.layer.borderColor = [UIColor colorWithRed:0.91 green:0.92 blue:0.92 alpha:1.00].CGColor;
    _xyLocalBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 300);
    [self xyReloaLocalViewWithTitle:@"北京市南门外大街123号"];

}

- (void)xyReloaLocalViewWithTitle:(NSString *)title{
    for(UIView * view in _xyLocalBtn.subviews){
        [view removeFromSuperview];
    }
    CGFloat imgH = xy(10);
    
    CGSize  strSize = [XYCommon xy_getSizeWithStr:title font:[UIFont systemFontOfSize:12] maxSize:CGSizeMake(WDScreenW, MAXFLOAT)];
    CGFloat xyX = (WDScreenW -  imgH - strSize.width - xyPadding)/2;
    
    
    UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(xyX,(CGRectGetHeight(_xyLocalBtn.frame) - imgH)/2, imgH, imgH*(30/24.00))];
    [_xyLocalBtn addSubview:imgView];
    [imgView setImage:[UIImage imageNamed:@"xy_icon-location"]];
    UILabel * titleLabel =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(imgView.frame) + xyPadding, 0, strSize.width, CGRectGetHeight(_xyLocalBtn.frame))];
    [_xyLocalBtn addSubview:titleLabel];
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.text = title;
    titleLabel.textColor = [UIColor colorWithRed:0.37 green:0.62 blue:0.88 alpha:1.00];
}

- (void)xyLayoutTextView{
    _xyTextView = [[XYTextView alloc]initWithFrame:CGRectMake(xyPadding, xyPadding + CGRectGetMaxY(_xyLocalBtn.frame), WDScreenW - xyPadding *2, xy(130))];
    [_xyHeaderView addSubview:_xyTextView];
    
    _xyTextView.layer.borderWidth = xy(0.5);
    _xyTextView.layer.borderColor = [UIColor colorWithRed:0.65 green:0.66 blue:0.66 alpha:1.00].CGColor;
    _xyTextView.placeholder= @"输入回访内容";
    _xyTextView.delegate = self;
}

- (void)xyLayoutRecordTextLabel{
    CGFloat labelW = xy(100);
    CGFloat labelH = xy(20);
    _xyRecordTextLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_xyTextView.frame) - labelW, xyPadding/2 + CGRectGetMaxY(_xyTextView.frame), labelW, labelH)];
    [_xyHeaderView addSubview:_xyRecordTextLabel];
    _xyRecordTextLabel.text = @"0/1000";
    _xyRecordTextLabel.textColor = [UIColor lightGrayColor];
    _xyRecordTextLabel.textAlignment = NSTextAlignmentRight;
    _xyRecordTextLabel.font = [UIFont systemFontOfSize:12];
}

- (void)xyLayoutCollectionView{
    
    UICollectionViewFlowLayout * xyLayout = [[UICollectionViewFlowLayout alloc]init];
    xyLayout.itemSize = CGSizeMake(xy(30), xy(30));
    xyLayout.minimumLineSpacing = xyPadding *2;
    xyLayout.minimumInteritemSpacing = xyPadding *2;
    xyLayout.headerReferenceSize = CGSizeMake(0, xyHeaderH);

    [xyLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

    _xyCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WDScreenW ,CGRectGetHeight(self.view.frame)- 54) collectionViewLayout:xyLayout];
    // 注册Cell
    _xyCollectionView.backgroundColor = [UIColor whiteColor];
    [_xyCollectionView registerClass:[XYAddPhotoCollectionCell class] forCellWithReuseIdentifier:@"xyCell"];
    
    [self.view addSubview:_xyCollectionView];
    _xyCollectionView.dataSource = self;
    _xyCollectionView.delegate = self;
    
    _xyItemW = xy(130);
    _xyItemH = 100*_xyItemW/135.00f;
    
    [_xyCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];

    
}

- (void)xyGetLocal{
    [_xyMapManager.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        else
        {
            //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
        }
        
        //根据定位信息，添加annotation
        MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
        [annotation setCoordinate:location.coordinate];
        
        //有无逆地理信息，annotationView的标题显示的字段不一样
        if (regeocode)
        {
            [annotation setTitle:[NSString stringWithFormat:@"%@", regeocode.formattedAddress]];
            [annotation setSubtitle:[NSString stringWithFormat:@"%@-%@-%.2fm", regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]];
            if(regeocode.formattedAddress.length >0){
                _xyLocalStr = regeocode.formattedAddress;
                [self xyReloaLocalViewWithTitle:regeocode.formattedAddress];
            }
            _xyLatitude = location.coordinate.latitude;
            _xyLongitude = location.coordinate.longitude;
        }
    
    }

    ];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(self.view.frame.size.width,xyHeaderH);
    }
    else {
        return CGSizeMake(0, 0);
    }
}

- (void)xyPushPhotoBroswerWithStyle:(LGShowImageType)style withIndexPath:(NSIndexPath*)indexPath{
    LGPhotoPickerBrowserViewController *BroswerVC = [[LGPhotoPickerBrowserViewController alloc] init];
    BroswerVC.delegate = self;
    BroswerVC.dataSource = self;
    BroswerVC.showType = style;
    _showType = style;
    NSInteger  num = indexPath.section*2+indexPath.row;

    BroswerVC.currentIndexPath = [NSIndexPath indexPathForRow:num inSection:0];
    
    [self presentViewController:BroswerVC animated:YES completion:nil];
}

- (void)xyPreareLGPhotosMArr{
    _xyLGPhotosMArr = [NSMutableArray array];
    _xyMarkMArr = [NSMutableArray array];
    if(_xyLGPhotosMArr.count!=_xyImgMArr.count){
        for(LGPhotoAssets * asset in _xyImgMArr){
            LGPhotoPickerBrowserPhoto *photo = [[LGPhotoPickerBrowserPhoto alloc] init];
            photo.photoImage = asset.originImage;
            [_xyLGPhotosMArr addObject:photo];
            
            NSMutableDictionary * checkDic = [NSMutableDictionary dictionary];
            [checkDic setObject:@"N" forKey:@"xyCellSelected"];
            [_xyMarkMArr addObject:checkDic];
            
        }
    }
    
   
   
}

//代理
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

}

- (void)textViewDidChange:(XYTextView *)textView{
    if (textView.hasText) { // textView.text.length
        textView.placeholder = @"";
        
    } else {
        textView.placeholder = @"输入回访内容";
        
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    NSString * str = [textView.text stringByReplacingCharactersInRange:range withString:text];
    _xyRecordTextLabel.text = [NSString stringWithFormat:@"%ld/1000",str.length];

    if(str.length >1000){
        [_xyTextView endEditing:YES];
        [XYHUD xy_showHudWithTitle:@"不能超过1000字~" withDelay:1];
    }else{
        
    }
    return YES;
}

#pragma mark - <UICollectionView代理>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_xyImgMArr.count == 0) {
        
        return 1;
        
    } else {
        
        return 2;
        
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    NSLog(@"几个:%ld",_xyImgMArr.count);
    if(_xyImgMArr.count == 0){
        return 1;
    }else{
        return (_xyImgMArr.count/2+1);

    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    XYAddPhotoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"xyCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.xyDelegate = self;
    NSInteger  num = indexPath.section*2+indexPath.row;
    cell.tag = num;

    NSLog(@"第几个:%ld,共有:%ld",num,_xyImgMArr.count);
    if(_xyImgMArr.count >0&&_xyImgMArr.count>num){
        LGPhotoAssets * assets = [_xyImgMArr objectAtIndex:num];
        [cell.xyImgView setImage:assets.originImage];
    }
    if((_xyImgMArr.count%2==0&&num>_xyImgMArr.count)){
        [cell.xyImgView setImage:nil];

    }
    if(_xyImgMArr.count==num){
        [cell.xyImgView setImage:[UIImage imageNamed:@"xy_icon_addPhoto"]];
        cell.xyCellMode = XYCellModeAdd;

    }else{
        cell.xyCellMode = XYCellModeBrowser;

    }
    
    NSMutableDictionary * mdic;
    if(_xyMarkMArr.count >num&&_xyMarkMArr.count!= 0){
        mdic=  _xyMarkMArr[num];
        NSString * check = [mdic objectForKey:@"xyCellSelected"];
        if([check isEqualToString:@"N"]){
            cell.xyIsChecked = NO;

        }else if([check isEqualToString:@"Y"]){
            cell.xyIsChecked = YES;

        }

    }else{
        cell.xyIsChecked = NO;

    }

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(_xyItemW, _xyItemH);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    UICollectionViewFlowLayout *flowLayout =
    (UICollectionViewFlowLayout *)collectionViewLayout;
    flowLayout.minimumInteritemSpacing = xyPadding *2;
    flowLayout.minimumLineSpacing = xyPadding *2;
    
    return UIEdgeInsetsMake(0,xyPadding , xyPadding *2, xyPadding);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XYAddPhotoCollectionCell * xyCell =(XYAddPhotoCollectionCell *) [collectionView cellForItemAtIndexPath:indexPath];
    
    NSLog(@"didSelectItemAtIndexSection:%ld,row:%ld,cell:%ld",indexPath.section,indexPath.row,xyCell.xyCellMode);
    
    
    if(_xyIsEdit){
        NSInteger num = (indexPath.row+indexPath.section *2);
        NSMutableDictionary * xyDic;
        if(_xyMarkMArr.count >num){
            xyDic= [_xyMarkMArr objectAtIndex:num];
            
        }
        
        if([[xyDic objectForKey:@"xyCellSelected"] isEqualToString:@"N"]){
            [xyDic setObject:@"Y" forKey:@"xyCellSelected"];
            xyCell.xyIsChecked = YES;
            [_xyWillDeleteMArr addObject:_xyImgMArr[num]];
        }else if([[xyDic objectForKey:@"xyCellSelected"] isEqualToString:@"Y"]){
            [xyDic setObject:@"N" forKey:@"xyCellSelected"];
            xyCell.xyIsChecked = NO;
            [_xyWillDeleteMArr removeObject:_xyImgMArr[num]];
            if(_xyWillDeleteMArr.count < 1){
                [self xyResetNormal];
            }

        }
    }else{
    
    if(xyCell.xyCellMode == XYCellModeBrowser){
        [self xyPushPhotoBroswerWithStyle:LGShowImageTypeImageBroswer withIndexPath:indexPath];
    }else if(xyCell.xyCellMode == XYCellModeAdd){
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择上传方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选取", nil];
        
        UIView *window = [UIApplication sharedApplication].keyWindow;
        [sheet showInView:window];

    }
    }
}

//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                            withReuseIdentifier:@"UICollectionViewHeader"
                                                                                   forIndexPath:indexPath];
    [headView addSubview:_xyHeaderView];
    
    return headView;
}

//代理
#pragma mark - <UIActionSheetDelegate>
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"选择:%ld",buttonIndex);
    switch (buttonIndex) {
        case 0:{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.delegate = self;
                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    [self presentViewController:picker animated:YES completion:nil];
            }else {
                    
                    [self showAlertWithMessage:@"请为致汇金服开放相册权限：手机设置->隐私->相机->致汇金服（打开）"];
                }
                
            
            
        }
            break;
        case 1:{
            
            
            [self presentPhotoPickerViewControllerWithStyle:LGShowImageTypeImagePicker];
            
                
            }
        
            break;
            
        default:
            break;
    }
    
}

//跳转控制器
- (void)presentPhotoPickerViewControllerWithStyle:(LGShowImageType)style
{
    // 创建控制器
    LGPhotoPickerViewController *pickerVc = [[LGPhotoPickerViewController alloc] initWithShowType:style];
    // 默认显示相册里面的内容SavePhotos
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // 最多能选20张图片
    pickerVc.maxCount = 20;
    pickerVc.delegate = self;
    _showType = style;
    [pickerVc showPickerVc:self];
}


#pragma mark - <LGPhotoPickerViewControllerDelegate>
- (void)pickerViewControllerDoneAsstes:(NSArray *)assets isOriginal:(BOOL)original
{
    NSLog(@"info:%@",assets);
    LGPhotoAssets *temp = nil;
    [_xyImgMArr addObjectsFromArray:assets];
    
    [_xyCollectionView reloadData];
    [self xyPreareLGPhotosMArr];
}

#pragma mark - LGPhotoPickerBrowserViewControllerDataSource

- (NSInteger)photoBrowser:(LGPhotoPickerBrowserViewController *)photoBrowser numberOfItemsInSection:(NSUInteger)section{if (_showType == LGShowImageTypeImageBroswer) {
    return self.xyLGPhotosMArr.count;
} else if (_showType == LGShowImageTypeImageURL) {
    return self.xyLGPhotosMArr.count;
} else {
    NSLog(@"非法数据源");
    return 0;
}
}

- (id<LGPhotoPickerBrowserPhoto>)photoBrowser:(LGPhotoPickerBrowserViewController *)pickerBrowser photoAtIndexPath:(NSIndexPath *)indexPath{
    if (_showType == LGShowImageTypeImageBroswer) {
        return [self.xyLGPhotosMArr objectAtIndex:indexPath.item];
        
    } else if (_showType == LGShowImageTypeImageURL) {
        return [self.xyLGPhotosMArr objectAtIndex:indexPath.item];
    } else {
        NSLog(@"非法数据源");
        return nil;
    }
}

- (void)xyPhotoCellLongTap:(UILongPressGestureRecognizer *)tap withCell:(id)cell{
    XYAddPhotoCollectionCell * xyCell = cell;
    if(_xyImgMArr.count <1){
        return;
    }
    _xyIsEdit = YES;
    NSInteger num = xyCell.tag;
    NSMutableDictionary * xyDic;
    if(_xyMarkMArr.count >num){
        xyDic= [_xyMarkMArr objectAtIndex:num];
        
    }
    
    if([[xyDic objectForKey:@"xyCellSelected"] isEqualToString:@"N"]){
        [xyDic setObject:@"Y" forKey:@"xyCellSelected"];
        xyCell.xyIsChecked = YES;
        [_xyWillDeleteMArr addObject:_xyImgMArr[num]];
    }
    
    [self loadNavItemWithLeftAction:@selector(xyCancelBtnClick:) leftBtnStr:@"取消" title:@"电话回访" rihgtAction:@selector(xySureBtnClick:) rightStr:@"删除"];

}

- (void)xyResetNormal{
    for(NSMutableDictionary * xyDic in _xyMarkMArr){
        [xyDic setObject:@"N" forKey:@"xyCellSelected"];
        
    }
    [self loadNavItemWithLeftAction:@selector(xyCancelBtnClick:) leftBtnStr:@"取消" title:@"电话回访" rihgtAction:@selector(xySureBtnClick:) rightStr:@"发布"];
    
    [_xyCollectionView reloadData];
    _xyIsEdit = NO;
    [_xyWillDeleteMArr removeAllObjects];
}

- (void)xyCommitFollow{
  NSDictionary *  paraDic = @{@"supplier_id":self.business.id,@"follow_id":_xyFollowId};
    [WDHTTPMethod xy_requestPostJsonWithUrl:xyUrl_commitFollow withItemClass:nil parameters:paraDic isAddCookie:YES success:^(id responseObject) {
        NSLog(@"errorCode:%@",[responseObject objectForKey:@"error_code"]);
        NSString * errorCode = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"error_code"]];
        NSString * errorMsg = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"error_msg"]];
        if([errorCode isEqualToString:@"0"]){
            [WDPromptBox showPromptBoxWithMassage:@"发布成功!"];
            [self xyPopVCWithVCClass:[WDBusinessDetailController class]];
            
        }else{
            [WDPromptBox showPromptBoxWithMassage:errorMsg];
            
            
        }
        [SVProgressHUD dismiss];

    } fail:^{
        [SVProgressHUD dismiss];

    }];
}

//事件
- (void)xyCancelBtnClick:(UIButton *)sender{
    NSLog(@"xyCancelBtnClick");

    if(_xyIsEdit){
        
        [self xyResetNormal];
    }else{
        [self showAlertWithTitle:@"提醒" Message:@"您是否要取消发布回访?" leftStr:@"是" rightStr:@"否" leftBtnClick:^{
            [self.navigationController popViewControllerAnimated:YES];
        } rightClick:^{
            
        }];
    }
    
}

- (void)xySureBtnClick:(UIButton *)sender{
    NSLog(@"xySureBtnClick");
    if(_xyIsEdit){
        [_xyImgMArr removeObjectsInArray:_xyWillDeleteMArr];
        [self xyResetNormal];
        [self xyPreareLGPhotosMArr];
        
    }else{
        [SVProgressHUD show];

    if(_xyTextView.text.length>0) {
        
        [self xyRequestCreateFollowSuccess:^(id responseObject) {
            
            NSDictionary * paraDic;
            if([self.xyFollowType isEqualToString:@"2"]){
                paraDic = @{@"follow_id":_xyFollowId};
                
                [self xyUploadPhotosWithImgArr:_xyImgMArr withParaDic:paraDic withSuccess:^(id responseObject) {
                    [self xyCommitFollow];
                }];
                
            }else if([self.xyFollowType isEqualToString:@"1"]){
                [self xyCommitFollow];

            }
            
            
        } fail:^{
            [SVProgressHUD dismiss];
        }];

        return;
    }
    [XYHUD xy_showHudWithTitle:@"内容不能为空" withDelay:1];
    }
}

- (void)xyPopVCWithVCClass:(Class)vcClass{
    for (UIViewController *vc in self.navigationController.viewControllers)
    {
        if ([vc isKindOfClass:vcClass])
        {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
}

- (void)xyShowLocalBtnClick:(UIButton *)sender{
    NSLog(@"xyShowLocalBtnClick");
    XYMapViewController * xyMapVC = [[XYMapViewController alloc]init];
    [self.navigationController pushViewController:xyMapVC animated:YES];
}

//请求

- (void)xyRequestCreateFollowSuccess:(void(^)(id responseObject))xySuccess fail:(void (^)())xyFail{
    NSDictionary * paraDic;
    if([self.xyFollowType isEqualToString:@"2"]){
        paraDic=@{@"supplier_id":self.business.id,@"type":self.xyFollowType,@"address":_xyLocalStr,@"longitude":[NSString stringWithFormat:@"%f",_xyLongitude],@"latitude":[NSString stringWithFormat:@"%f",_xyLatitude],@"content":_xyTextView.text};

    }else if([self.xyFollowType isEqualToString:@"1"]){
        paraDic=@{@"supplier_id":self.business.id,@"type":self.xyFollowType,@"content":_xyTextView.text};

    }
    
    [WDHTTPMethod xy_requestPostJsonWithUrl:xyUrl_createFollow withItemClass:nil parameters:paraDic isAddCookie:YES success:^(id responseObject) {
        NSLog(@"创建跟进:%@",responseObject);
        _xyFollowId = [responseObject objectForKey:@"follow_id"];
        NSString * code = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"error_code"]];

        
        if(xySuccess){
            if([code isEqualToString:@"0"]){
                xySuccess(_xyFollowId);

            }
        }
    } fail:^{
        
    }];
}

- (void)xyUploadPhotosWithImgArr:(NSMutableArray *)imgArr withParaDic:(id)paraDic withSuccess:(void(^)(id responseObject))success {
    
    for(NSInteger i=0; i<imgArr.count;i++){
        LGPhotoAssets * asset = imgArr[i];
            
        UIImage * img = asset.originImage;

        NSData * imgData = UIImageJPEGRepresentation(img,1);
    

        [WDHTTPMethod xy_requestPostUploadWithUrl:xyUrl_photoUpload withItemClass:nil withImgData:imgData withName:@"file" withParameters:paraDic success:^(id responseObject) {
            
            NSString * error_code = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"error_code"]];
            if([error_code isEqualToString:@"0"]){
                NSLog(@"上传图片成功!");
                if(i==(imgArr.count -1)){
                    success(error_code);
                }
            }
            
        } fail:^{
            
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
